package cmdb

import (
	"fmt"
	"time"

	"gitee.com/ChangPaoZhe/client/config"
	"gitee.com/ChangPaoZhe/devops/apps/cmdb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"context"
)

// 用于调用服务端完成注册


func NewDefaultRegisterRequest()  *cmdb.RegisterRequest{
	return  &cmdb.RegisterRequest{
		Key: "Mysql#12345",
		Resource: &cmdb.Resource{
			Ipaddress: "192.168.1.254",
			SystemName: "linux",
			Region: "gz",
			Hostname: "localhost",
			Username: "root",
			Password: "1",
			Port: 22,
			Create_At: time.Now().Unix(),
		},
	}
}

func  (c  *CmdbImpl)  Register()  {
	Ctx,_:=context.WithTimeout(context.Background(), time.Second)
	in:=NewDefaultRegisterRequest()
	resource:=&cmdb.Resource{}
	conn,err:=grpc.Dial(config.C.GrpcServer.GetAddress(),grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err!=nil {
		c.logger.Error().Msg(fmt.Sprintf("注册调用失败:%s",err))
	}
	defer conn.Close()
	client:=cmdb.NewRPCClient(conn)
	resources,err:=client.Search(Ctx, &cmdb.SearchRequest{
		Region: in.Resource.Region,
		Ipaddress: in.Resource.Ipaddress,
	})
	if err !=nil  {
		c.logger.Error().Msg(err.Error())
		resource,err=client.Register(Ctx, in)
		if err!=nil {
			c.logger.Error().Msg(err.Error())
		}
		c.logger.Info().Msg(resource.String())
	}else {
		c.logger.Info().Msg(resources.String())
	}
}
func  (c  *CmdbImpl)  Healther() {
	health:=&cmdb.RequestHealth{
		Region: "gz",
		IpAddress: "192.168.1.254",
	}
	Ctx,_:=context.WithTimeout(context.Background(), time.Second)
	conn,err:=grpc.Dial(config.C.GrpcServer.GetAddress(),grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err!=nil {
		panic(err)
	}
	client:=cmdb.NewRPCClient(conn)
	response,err:=client.Healther(Ctx, health)
	
	if err != nil {
		c.logger.Error().Msg(err.Error())
	}
	defer conn.Close()
	c.logger.Info().Msg(response.String())
}